package com.localcache.server.controller;

import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.localcache.server.cache.CacheConstants;
import com.localcache.server.init.Initializer;
import com.localcache.server.service.CacheDataInfo;
import com.localcache.server.service.DlcCacheServerService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.Map;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * TODO
 *
 * @author chennengcheng
 * @date 2022-05-25 17:11
 * @remark
 */

@Slf4j
@RestController
@RequestMapping("/main")
public class CacheFlushDataController {

    @Autowired
    private DlcCacheServerService dlcCacheServerService;

    // 1. 获取所有的已连接的本地缓存服务
    // 2. 刷新指定服务的本地缓存
    /**
     * 该接口用于给阿里云检测
     *
     * @return 默认返回
     */
    @GetMapping("/flushCurrentCacheData")
    public String flushCurrentCacheData(@RequestParam("key") String key){
        dlcCacheServerService.flushCurrentCacheData(key);
        return "ok";
    }


    @GetMapping("/openLocalCache")
    public String openLocalCache(@RequestParam("key") String key){
        dlcCacheServerService.openCache(key);
        return "ok";
    }

    @GetMapping("/closeLocalCache")
    public String closeLocalCache(@RequestParam("key") String key){
        dlcCacheServerService.closeCache(key);
        return "ok";
    }

    @GetMapping("/getCurrentCache")
    public String getCurrentCache(@RequestParam("key") String key){
        // 开始获取
        dlcCacheServerService.getCurrentCache(key);
        return "正在获取中....";
    }

    @GetMapping("/listAllCache")
    public String listAllCache(@RequestParam(value = "key", required = false) String key, @RequestParam(value = "activeProfile") String activeProfile){
        Map<String, CacheDataInfo> result = CacheConstants.cacheReportDateMap.entrySet()
                .stream()
                .filter(v -> v.getKey().contains(activeProfile))
                .filter(v -> v.getKey().contains(key))
                .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue));
        return JSONUtil.toJsonStr(result);
    }

    @RequestMapping("/downloadCacheData")
    public String downloadCacheData(@RequestParam("key") String key, HttpServletResponse response) throws Exception {
        if (key != null) {
            // 1. 判断是否正在下载中 , 如果正在下载，则不让其生成
            Boolean isDownloading = DlcCacheServerService.fileDownloadStatus.get(key);
            if (Objects.nonNull(isDownloading) && isDownloading) {
                log.error("正在下载实时缓存数据中: " + key);
                return "正在下载实时缓存数据中";
            }

            Boolean isGenerator = CacheConstants.tempCacheFileGenerateStatusMap.get(key);
            if (Objects.nonNull(isGenerator) && isGenerator) {
                log.error("正在生成实时缓存数据中: " + key);
                return "正在生成实时缓存数据中";
            }

            // 2. 设置状态为，正在生成数据中
            DlcCacheServerService.fileDownloadStatus.put(key, true);
            String fileName = key.replaceAll(StrUtil.COLON, "-" ) + ".zip";
            String filePathZip = Initializer.getSystemPath() + fileName;
            File file = new File(filePathZip);
            if (file.exists()) {
                response.setContentType("application/octet-stream");
                response.setHeader("content-type", "application/octet-stream");
                response.setHeader("Content-Disposition", "attachment;fileName=" + fileName);// 设置文件名
                byte[] buffer = new byte[1024];
                FileInputStream fis = null;
                BufferedInputStream bis = null;
                try {
                    fis = new FileInputStream(file);
                    bis = new BufferedInputStream(fis);
                    OutputStream os = response.getOutputStream();
                    int i = bis.read(buffer);
                    while (i != -1) {
                        os.write(buffer, 0, i);
                        i = bis.read(buffer);
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                } finally {
                    if (bis != null) {
                        try {
                            bis.close();
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
                    if (fis != null) {
                        try {
                            fis.close();
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }

                    DlcCacheServerService.fileDownloadStatus.put(key, false);
                }
            }
        }
        return null;
    }

}
